package top.sneaker.common.core.launch;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 公共启动类
 *
 * @author zhaowx
 * @date 2022/4/22 0022
 */
public class SubApplication {

    private final static String DEFAULT_ENV = "dev";

    public SubApplication() {
    }

    /**
     * 程序应用上下文
     *
     * @param appName 应用程序名称
     * @param clazz   应用启动类class
     * @param args    启动参数
     * @return {@code ConfigurableApplicationContext}
     */
    public static ConfigurableApplicationContext run(String appName, Class clazz, String... args) {
        SpringApplicationBuilder builder = createSpringApplicationBuilder(appName, clazz, args);
        return builder.run(args);
    }

    /**
     * 创建应用构造器
     *
     * @param appName 应用程序名称
     * @param clazz   应用启动类class
     * @param args    启动参数
     * @return {@code SpringApplicationBuilder}
     */
    public static SpringApplicationBuilder createSpringApplicationBuilder(String appName, Class clazz, String... args) {
        Assert.hasText(appName, "服务名不可为空！");
        // 获取环境对象
        ConfigurableEnvironment environment = new StandardEnvironment();
        // 获取当前环境变量
        String[] activeProfiles = environment.getActiveProfiles();
        List<String> profiles = Arrays.asList(activeProfiles);

        // builder
        SpringApplicationBuilder builder = new SpringApplicationBuilder(clazz);

        // 环境变量名称
        String profile;
        if (profiles.isEmpty()) {
            profile = DEFAULT_ENV;
            profiles.add(profile);
            builder.profiles(profile);
        } else {
            if (profiles.size() != 1) {
                throw new RuntimeException("同时存在环境变量:[" + StringUtils.arrayToCommaDelimitedString(activeProfiles) + "]");
            }

            profile = profiles.get(0);
        }

        System.out.printf("----启动中，读取到的环境变量:[%s]----%n", profile);

        LauncherClient client = new LauncherClient();
        client.launcher(builder, appName, profile);

        return builder;
    }

}
